package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@Transactional
// 收货地址
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    //查询地址
    @Override
    public List<Address> list() {
        //select * from Address_book where  UserId =id
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());


        return addressMapper.selectList(qw);
    }

    //新增地址
    @Override
    public void save(Address address) {
        //补全数据
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0); // 是否默认地址
        //添加数据
        addressMapper.insert(address);

    }

    //修改默认地址
    @Override
    public void defaultSet(Address newAddress) {
        // update address_book set is_default=0 where user_id = ?
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        Address oldAdress = new Address();
        oldAdress.setIsDefault(0);
        addressMapper.update(oldAdress, qw);
        // 2.把新传递地址设置为默认
        newAddress.setIsDefault(1); // 默认
        addressMapper.updateById(newAddress);
    }

    //查看默认地址
    @Override
    public Address findDefault() {
        //select * from   address_book set is_default=1 where user_id =id

        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getIsDefault, 1);
        qw.eq(Address::getUserId, UserHolder.get().getId());
        Address address = addressMapper.selectOne(qw);

        return address;
    }

    //查看所有地址
    @Override
    public Address selectById(Long id) {
        //select * from   address_book  where id=?
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getId, id);
        Address address = addressMapper.selectOne(qw);
        log.info(String.valueOf(address.getId()));
        return address;
    }

    //修改地址信息
    @Override
    public void update(Address address) {

        addressMapper.updateById(address);
    }


}
